/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.send.method
 */
package com.apache.portal.common.template.method;

import java.io.UnsupportedEncodingException;
import java.util.List;

import com.apache.uct.common.ToolsUtil;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * description:  格式化Long类型时间
 */
public class SubStringMethod implements TemplateMethodModel {

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)  
	 */
	public Object exec(List arguments) throws TemplateModelException {
		if (!ToolsUtil.isEmpty(arguments) && arguments.size() > 1) {
			String str = String.valueOf(arguments.get(0));
			int length = Integer.valueOf(arguments.get(1).toString());
			String defStr = "";
			if (arguments.size() > 1)
				defStr = String.valueOf(arguments.get(2));
			try {
				return getTitleToTen(str, length, defStr);
			} catch (Exception e) {
			}
		}
		return "";
	}

	private String getTitleToTen(String str, int length, String defStr) throws Exception {
		int textLength = str.length();
		int byteLength = 0;
		StringBuffer returnStr = new StringBuffer();
		for (int i = 0; i < textLength && byteLength < length * 2; i++) {
			String str_i = str.substring(i, i + 1);
			if (str_i.getBytes().length == 1) {//英文  
				byteLength++;
			} else {//中文  
				byteLength += 3;
			}
			returnStr.append(str_i);
		}
		try {
			if (byteLength < str.getBytes("UTF-8").length) {//getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3  
				returnStr.append(defStr);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return returnStr.toString();
	}

}
